import os,urllib, csv, stockdetails,datetime
#from BeautifulSoup import BeautifulSoup
import subprocess

def timeStamped(fname, fmt='%Y-%m-%d-%H-%M-%S_{fname}'):
    return datetime.datetime.now().strftime(fmt).format(fname=fname)

def tempDir():
    if (os.path.exists(os.getenv("temp", ) + '\\data\\') <> True):
        os.mkdir(os.getenv("temp", ) + '\\data\\')
    return os.getenv("temp", ) + '\\data\\'

def open_ex(dir_path):
    subprocess.Popen('explorer '+ tempDir())   
    return

s = 'ABX'
opt = {}              
allfiledata = {}
datafiles = os.listdir(tempDir())
quotefields =  ["strike","code","last","change","bid","offer","vol","open_int","stock","exp","spot","link"]
open_ex(tempDir())

w = csv.writer(open(tempDir() + 'output for ' + s + '.csv', 'wb'))

for df in datafiles:
    fn = tempDir() + '\\' + df
    f = open(fn, 'rb')
    mainReader = csv.DictReader( f,quotefields ,"data")
    data = {}
    for line in mainReader:
        data[line['code']] = line
    allfiledata[df.replace('_options for ' + s + '.csv','')] = data    

for i in allfiledata:
    snap = allfiledata.get(i)
    for x in snap:
        opt = snap.get(x)
        if opt['stock'] == s:
            temp = []
            temp.append(i)
            for item in quotefields:
                temp.append(opt[item])
            print temp
            w.writerow(temp)
  